//
//  LoginVC.m
//  sensen_ios
//
//  Created by pro on 16/2/1.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "LoginVC.h"


#import "PersonalVC.h" //个人中心
#import "RegisterVC.h" // 登陆
#import "ForgetPwdVC.h" // 忘记密码
#import "MsgLoginVC.h" // 短信登陆

#import "UserOperationView.h"

#import "MobileBindVC.h"

#import "WXApi.h"




@interface LoginVC ()<WXApiDelegate>

@property (nonatomic, strong) UserOperationView *userView;
@end

@implementation LoginVC

-(void) dealloc{
    NSLog(@"LoginVC dealloc");
    
//    [SVProgressHUD showOnlyStatus:@"销毁登录界面" withDuration:3];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"weixinLogin" object:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"登录";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createLeftBarButtonItemWithImagename:nil]; // 左侧返回按钮
    [self createRightBarButtonItemWithTitle:@"注册"]; // 右侧注册按钮
    
    [self _createViews]; // 创建视图
    
    //监听微信登陆
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getWeChatLoginCode:) name:@"weixinLogin" object:nil];
    
//    [SVProgressHUD showOnlyStatus:@"监听微信登录" withDuration:3];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    // 设置导航栏颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    [self.view endEditing:YES];
    
}

#pragma mark - 创建视图
- (void)_createViews {
    
    [self _createLogoView];
    [self _createUserView];
    [self _createButtons];
    [self _createOtherLoginViews];
}

// 创建logo视图
- (void)_createLogoView {
    CGFloat x = 0;
    CGFloat y = 20;
    CGFloat width = SCREEN_HEIGHT * 0.12;
    CGFloat height = width;
    
    // logo图标
    UIImageView *logoImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    logoImgView.image = [UIImage imageNamed:@"登陆_logo"];
    [self.scrollView addSubview:logoImgView];
    logoImgView.center = CGPointMake(SCREEN_WIDTH / 2.0, logoImgView.center.y);
    
    // logo label
    y = logoImgView.bottom;
    width = SCREEN_WIDTH * 0.4;
    height = logoImgView.height / 2.0;
    UILabel *logoLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    logoLabel.font = FONT(height / 1.5);
    logoLabel.text = @"森森休闲";
    logoLabel.textColor = SS_NAVI_ORANGE_COLOR;
    logoLabel.textAlignment = NSTextAlignmentCenter;
    [self.scrollView addSubview:logoLabel];
    logoLabel.center = CGPointMake(SCREEN_WIDTH / 2.0, logoLabel.center.y);
    logoLabel.tag = 1;
}
// 创建用户操作视图（登陆，注册等）
- (void)_createUserView {
    
    UIView *logoLabel = [self.view viewWithTag:1];
    
    _userView = [[UserOperationView alloc] initWithFrame:CGRectMake(0, logoLabel.bottom + 20, SCREEN_WIDTH, lineHeight * 2)
                                                  titles:@[@"手机号", @"登录密码"]
                                                    type:ZKUserViewLogin];
    [self.scrollView addSubview:_userView];
}
- (void)_createButtons {
    CGFloat x = 20;
    CGFloat y = _userView.bottom + 20;
    CGFloat width = SCREEN_WIDTH - 2 * x;
    CGFloat height = 40;
    
    // 登录按钮
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.frame = CGRectMake(x, y, width, height);
    loginButton.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    [loginButton setTitle:@"登录" forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginButton addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    loginButton.layer.cornerRadius = 2;
    [self.scrollView addSubview:loginButton];
    loginButton.tag = 99;
    loginButton.enabled = NO;
    
    // 忘记密码按钮
    y = loginButton.bottom + 10;
    width = loginButton.width / 2.0;
    height = 20;
    UIButton *forgetPwdButton = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetPwdButton.frame = CGRectMake(x, y, width, height);
    forgetPwdButton.backgroundColor = [UIColor clearColor];
    [forgetPwdButton setTitle:@"忘记密码 ?" forState:UIControlStateNormal];
    [forgetPwdButton setTitleColor:SS_NAVI_ORANGE_COLOR forState:UIControlStateNormal];
    [forgetPwdButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    forgetPwdButton.titleLabel.font = FONT(15);
    [forgetPwdButton addTarget:self action:@selector(forgetPwdAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:forgetPwdButton];
    
    // 短信验证登陆按钮
    x = forgetPwdButton.right;
    UIButton *msgLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    msgLoginButton.frame = CGRectMake(x, y, width, height);
    msgLoginButton.backgroundColor = [UIColor clearColor];
    [msgLoginButton setTitle:@"短信验证登录" forState:UIControlStateNormal];
    [msgLoginButton setTitleColor:SS_NAVI_ORANGE_COLOR forState:UIControlStateNormal];
    [msgLoginButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    msgLoginButton.titleLabel.font = FONT(15);
    [msgLoginButton addTarget:self action:@selector(msgLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:msgLoginButton];
}
// 三方登陆
- (void)_createOtherLoginViews {
    // 第三方登陆 label
    CGFloat x = 0;
    CGFloat y = 0;
    CGFloat width = 100;
    CGFloat height = 20;
    UILabel *otherLoginLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    otherLoginLabel.font = FONT(16);
    otherLoginLabel.text = @"第三方登录";
    otherLoginLabel.textColor = [UIColor darkGrayColor];
    otherLoginLabel.textAlignment = NSTextAlignmentCenter;
    [self.scrollView addSubview:otherLoginLabel];
    
    // 分割线
    x = 30;
    width = SCREEN_WIDTH - 2 * x;
    height = 1;
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    line.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
    [self.scrollView addSubview:line];
    
    // 微信 图标
    height = 74 / 2.0;
    width = 92 / 2.0;
    y = SCREEN_HEIGHT - 64 - 20 - height;
    UIImageView *wxImgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    wxImgView.userInteractionEnabled = YES;
    [wxImgView setContentMode:UIViewContentModeScaleAspectFill];
    wxImgView.image = [UIImage imageNamed:@"微信登陆"];
    [self.scrollView addSubview:wxImgView];
    // 给微信图标添加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(wxLogin:)];
    [wxImgView addGestureRecognizer:tap];
    
    // 设置位置
    // 微信图标的位置
    wxImgView.center = CGPointMake(SCREEN_WIDTH / 2.0, wxImgView.center.y);
    // 分割线的位置
    line.bottom = wxImgView.top - 20;
    // label的位置
    otherLoginLabel.bottom = line.top - 10;
    otherLoginLabel.center = CGPointMake(SCREEN_WIDTH / 2.0, otherLoginLabel.center.y);
    
}


#pragma mark -- 微信登陆相关 --
-(void) onReq:(BaseReq*)req{
    DLog(@"onReq");
    
}

/*! @brief 发送一个sendReq后，收到微信的回应
 *
 * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
 * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
 * @param resp具体的回应内容，是自动释放的
 */
-(void) onResp:(BaseResp*)resp{
    
    DLog(@"onResp");
    
    if (resp == nil) {
        NSLog(@"不能为空!");
        return;
    }
    
    // 登陆
    if([resp isKindOfClass:[SendAuthResp class]]) {
        
        SendAuthResp *temp = (SendAuthResp*)resp;
        if (temp.errCode== 0) {
            
            NSString *code = temp.code;
            NSString *state = temp.state;
            
            NSDictionary *dictionary = @{@"code":code,@"state":state};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"weixinLogin" object:self userInfo:dictionary];
        }
    }

    
}

// 微信登陆点击事件，在此点击后appDelegate中就会发送通知，然后再这里接收到通知获得code
- (void)wxLogin:(UITapGestureRecognizer *)tap {
    [self _sendAuthRequest];
}

-(void)_sendAuthRequest
{
    
    //构造SendAuthReq结构体
    SendAuthReq* req =[[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.state = @"ss_weixin";
    
    //第三方向微信终端发送一个 SendAuthReq 消息结构
    if(![WXApi sendAuthReq:req viewController:self delegate:self]){
        [SVProgressHUD showOnlyStatus:@"微信登录请求发起失败" withDuration:3];
    }
    
}

// 微信登陆通知方法
-(void)getWeChatLoginCode:(NSNotification *)notification{
    
    NSString *code = [[notification userInfo] objectForKey:@"code"];
    NSString *state = [[notification userInfo] objectForKey:@"state"];
    
    [SVProgressHUD showOnlyStatus:@"收到微信登录响应" withDuration:3];
    if (![state isEqualToString:@"ss_weixin"]) {
        [SVProgressHUD showErrorWithStatus:@"登录失败，请重试!" withDuration:3];
        return;
    }
    
    __weak   LoginVC * that = self;
      NSLog(@"code = %@", code);
    
    NSDictionary *params = @{@"code":code};
    [SVProgressHUD showWithStatus:@"正在登录中..."];
    [BoyeHttpClient post:@"BY_Weixin_login" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        
        NSLog(@"微信登陆:%@", result);
        UserModel * user = [[UserModel alloc] initContentWithDic:result];
        NSLog(@"微信登录手机号  %@", user.mobile);
        [SVProgressHUD dismiss];
        [BoyeHttpClient post:@"BY_BbsUserCenter_getUserInfo" apiVerson:100 params:@{@"uid":user.uid} success:^(AFHTTPRequestOperation *operation, id result) {
            if (![result[@"group"] isKindOfClass:[NSNull class]]) {
                NSDictionary *groupDic = result[@"group"];
                user.allowdelpost = groupDic[@"allowdelpost"];
                user.allowstickthread = groupDic[@"allowstickthread"];
                user.allowdigestthread = groupDic[@"allowdigestthread"];
                user.allowpost = groupDic[@"allowpost"];
                user.fid = groupDic[@"fid"];
            }
            
            
            // 友盟添加别名（根据别名推送）
            [UMessage addAlias:user.uid type:@"sunsun" response:^(id responseObject, NSError *error) {
                NSLog(@"添加%@", responseObject);
                NSLog(@"%@", [NSThread currentThread]);
            }];
            
            NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:1];
            
            NSLog(@"设备的唯一标识 = %@", [[CacheFacade sharedCache] get:Device_Token]);
            [dic setObject:[NSString stringWithFormat:@"%@", [[CacheFacade sharedCache] get:Device_Token]] forKey:@"device_token"];
            
            NSLog(@"uid = %@", user.uid);
            
            [dic setObject:user.uid forKey:@"uid"];
            [dic setObject:[NSString deviceVersion] forKey:@"version"];
            [dic setObject:@"ios" forKey:@"device_type"];
            
            
            [BoyeHttpClient post:@"BY_Device_bind" apiVerson:100 params:dic success:^(AFHTTPRequestOperation *operation, id result) {
                [SVProgressHUD dismiss];
                
                if (user.mobile.length > 0) {
                    [that setLoginInfo:user];
                }else{
                    MobileBindVC *vc = [[MobileBindVC alloc] init];
                    [CommonCache setUserInfo:user];
                    [self.navigationController pushViewController:vc animated:YES];
                }

            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"登录名或密码错误，请重新登录" withDuration:1.5];
            }];

            
            
            
            
         
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@",error.domain] withDuration:1];
        }];

        
        
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"登录失败,请重试"] withDuration:3];
        NSLog(@"wechat_login_error:%@", error);
    }];
    
}

-(void) setLoginInfo:(UserModel * )user{
    if(user != nil){
        [CommonCache setUserInfo:user];
        // 登录成功后跳转到首页
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }else{
        //TODO: 登录失败
        [SVProgressHUD showErrorWithStatus:@"登录失败,请重试" withDuration:3];
    }
}




#pragma mark - 点击事件 
- (void)leftAction:(UIButton *)button {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 登陆
- (void)loginAction:(UIButton *)button {
    [_APP_KEYWINDOW endEditing:YES]; // 隐藏键盘
    [SVProgressHUD showWithStatus:@"登录中..." maskType:SVProgressHUDMaskTypeBlack];
    [_userView getLoginInfo:^(NSDictionary *infoDic) {
        
        NSString *mobile = infoDic[@"mobile"];
        NSString *password = infoDic[@"password"];
        
        [BoyeHttpClient post:@"BY_User_Login" apiVerson:100 params:@{@"username" : mobile, @"password" : password} success:^(AFHTTPRequestOperation *operation, id result) {
            if ([result isKindOfClass:[NSDictionary class]]) {
                
                NSLog(@"已绑定微信的手机号登录  ＝%@", result);
                // 用户信息存储到本地
                NSDictionary *resultDic = result;
                UserModel *user = [[UserModel alloc] initContentWithDic:resultDic];
                [BoyeHttpClient post:@"BY_BbsUserCenter_getUserInfo" apiVerson:100 params:@{@"uid":user.uid} success:^(AFHTTPRequestOperation *operation, id result) {
                    if (![result[@"group"] isKindOfClass:[NSNull class]]) {
                        NSDictionary *groupDic = result[@"group"];
                        user.allowdelpost = groupDic[@"allowdelpost"];
                        user.allowstickthread = groupDic[@"allowstickthread"];
                        user.allowdigestthread = groupDic[@"allowdigestthread"];
                        user.allowpost = groupDic[@"allowpost"];
                        user.fid = groupDic[@"fid"];
                    }
                    
                    
                    // 友盟添加别名（根据别名推送）
                    [UMessage addAlias:user.uid type:@"sunsun" response:^(id responseObject, NSError *error) {
                        NSLog(@"添加%@", responseObject);
                        NSLog(@"%@", [NSThread currentThread]);
                    }];
                    
                    
                    NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:1];
                    
                    NSLog(@"设备的唯一标识 = %@", [[CacheFacade sharedCache] get:Device_Token]);
                    [dic setObject:[NSString stringWithFormat:@"%@", [[CacheFacade sharedCache] get:Device_Token]] forKey:@"device_token"];
                    NSLog(@"uid = %@", user.uid);
                    [dic setObject:user.uid forKey:@"uid"];
                    [dic setObject:[NSString deviceVersion] forKey:@"version"];
                    [dic setObject:@"ios" forKey:@"device_type"];
                    
                    [BoyeHttpClient post:@"BY_Device_bind" apiVerson:100 params:dic success:^(AFHTTPRequestOperation *operation, id result) {
                        [SVProgressHUD showSuccessWithStatus:@"登录成功" withDuration:1];
                        NSLog(@"设备绑定 %@", result);
                        [CommonCache setUserInfo:user];
                        [self dismissViewControllerAnimated:YES completion:nil];  // 返回到跳过来的页面

                        
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                        
                       [SVProgressHUD showErrorWithStatus:@"登录名或密码错误，请重新登录" withDuration:1.5];
                        
                    }];
                    
                    
                    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    [SVProgressHUD showErrorWithStatus:error.domain withDuration:1.5];
                }];
                
                
                
            } else {
                [SVProgressHUD showErrorWithStatus:result withDuration:1.5];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@", error);
            [SVProgressHUD showErrorWithStatus:@"登录名或密码错误，请重新登录" withDuration:1.5];
        }];
    }];
    
}


// 注册
- (void)rightAction:(UIButton *)button {
    RegisterVC *vc = [[RegisterVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
// 忘记密码
- (void)forgetPwdAction:(UIButton *)button {
    ForgetPwdVC *vc = [[ForgetPwdVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
// 短信登陆
- (void)msgLoginAction:(UIButton *)button {
    MsgLoginVC *vc = [[MsgLoginVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 其他
// 输入框内容改变通知事件
- (void)allTextFieldEndEditing {
    UIButton *loginButton = [self.view viewWithTag:99];
    if ([_userView isAllTextFieldEdited]) {
        loginButton.backgroundColor = SS_NAVI_ORANGE_COLOR;
        loginButton.enabled = YES;
    } else {
        loginButton.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1];
        loginButton.enabled = NO;
    }
}







#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
